import { useModel } from "umi";
import { Popconfirm, Input, List, Space, message } from "antd";
import { useReactive } from "ahooks";

import { AddMember } from "../../_graphql/platforms";

const AddMemberModal = ({ members, reloadData }) => {
    const { graphqlFetchPlatform, remoteData, UTCTimeToLocal } = useModel("global");
    const { onCloseGlobalModal } = useModel("global.modal");
    const { loginInfo } = useModel("person.info");

    const state = useReactive({
        loading: false,
        persons: [],
    });

    const handleSearchMember = async (value) => {
        if (value && loginInfo?.authCenterUrl) {
            state.loading = true;
            let res = await remoteData({
                object: "public-user-auth-center",
                serviceUrl: loginInfo.authCenterUrl,
                serviceName: "/api/v1/person/searchRealName",
                params: { realName: value },
            });
            state.persons = res || [];
            state.loading = false;
        } else {
            message.warning("名称不能为空");
        }
    };

    const add = async (item) => {
        state.loading = true;
        let saveData = {
            pmAvta: item.avatarHash,
            pmBirt: item.birthday,
            pmJoti: new Date().getUTCTime(),
            pmName: item.realName,
            pmPhone: item.phone,
            pmRoge: item.sex,
            pmUuid: item.uuid,
            pmAust: true,
        };
        let res = await graphqlFetchPlatform({ query: AddMember, variables: saveData });
        if (res) {
            message.success("成功添加管理员");
            reloadData();
            onCloseGlobalModal();
        }
        state.loading = false;
    };

    return (
        <Space direction="vertical" size={20} style={{ width: "100%" }}>
            <Input.Search placeholder="搜索人员姓名" onSearch={handleSearchMember} allowClear enterButton />
            <List
                loading={state.loading}
                header={"人员列表"}
                bordered
                size="small"
                dataSource={state.persons}
                renderItem={(item) => {
                    let actions = [];
                    if (members.findIndex((_item) => _item.pmUuid === item.uuid) === -1) {
                        actions.push(
                            <Popconfirm title="确定要添加当前人员吗?" placement="topRight" onConfirm={() => add(item)}>
                                <a>添加</a>
                            </Popconfirm>
                        );
                    } else {
                        actions.push("已授权");
                    }
                    return (
                        <List.Item actions={actions}>
                            {item.realName} {state.persons.length > 1 && item.phone && `(${item.phone})`}
                        </List.Item>
                    );
                }}
            />
        </Space>
    );
};

export default AddMemberModal;
